var express = require('express');
var router = express.Router();

var {WhuserModel} = require("../utils/model")
var {aesEncrypt} = require("../utils/index")

var moment = require("moment")
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get("/login",(req,res)=>{
  res.send("恭喜你,登录成功....")
})


router.get("/getsome",(req,res)=>{
  res.send("getsome-getsome...")
})


router.post("/register",(req,res)=>{
   var body = req.body;
   console.log(body)
  //  先判断是否已经插入 
  //  如果没有插入 就直接新增插入
  //  如果 有  就提示 已经被注册  

  WhuserModel.findOne({
    $or:[
     { username:body.username},
     {phone:body.phone}
    ]
  })
  .then(data=>{
    console.log(data)
     if(data){  
      res.send(`<script>alert('注册失败,当前账号已被注册.');location.href='/register'</script>`)
     }else{
      //  注册
      body.time = new Date();
      WhuserModel.insertMany(body)
      .then(result=>{
         res.send(`<script>alert('注册成功,请登陆.');location.href='/login?username=${aesEncrypt(body.username)}'</script>`)
      })
      .catch(err=>{
        res.send(`<script>alert('注册失败,未知错误.');location.href='/register' </script>`)
      })
     }
  })
   
})


router.post("/signin",(req,res)=>{
    var body = req.body; 
    WhuserModel.findOne({
        $or:[
          {
            username:body.username
          },
          {
            phone:body.phone
          }
        ]
    }).then(result=>{
        console.log(result);
        
        if(result.pass==body.pass){
           req.session.username = result.username;
           req.session.phone = result.phone
           req.session.loginTime = moment().format("YYYY-MM-DD HH:mm:ss");
           res.redirect('/')   // 重定向  

        }else{
          res.send(`<script>alert('登陆失败,用户名或者密码错误.');location.href='/login'</script>`)
        }
    }).catch(err=>{
      res.send(`<script>alert('登陆失败,未知错误.');location.href='/login' </script>`)
    })
})
module.exports = router;
